package com.itheima.app.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.mongo.yuyin.Sound;
import com.itheima.domain.mongo.yuyin.SoundVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.yuyin.SoundService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Component
public class SoundManager {


    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @Autowired
    FdfsWebServer fdfsWebServer;

    @DubboReference
    SoundService soundService;


    @DubboReference
    UserInfoService userInfoService;


    public void saveSound(Long userId, MultipartFile soundFile) throws IOException {


        //2.把英语频存入fastDFS
        StorePath storePath = fastFileStorageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(),
                FileUtil.extName(soundFile.getOriginalFilename()), null);


        Sound sound = new Sound();

        UserInfo userInfo = userInfoService.findByUserId(userId);


        sound.setUserId(userId);
        sound.setCreated(System.currentTimeMillis());
        sound.setLoveCount(0);
        sound.setUrl(fdfsWebServer.getWebServerUrl()+storePath.getFullPath());
        sound.setGender(userInfo.getGender());
        soundService.save(sound);

    }

    public ResponseEntity findByPhone() {

        Long userId = UserHolder.get().getId();

        UserInfo userInfo = userInfoService.findByUserId(userId);

        String gender = userInfo.getGender();

        Sound serviceBySound = soundService.findBySound(gender);

        if (serviceBySound !=null) {
            SoundVo soundVo = new SoundVo();

            UserInfo byUserId = userInfoService.findByUserId(serviceBySound.getUserId());

            soundVo.setAge(byUserId.getAge());
            soundVo.setAvatar(byUserId.getAvatar());
            soundVo.setGender(byUserId.getGender());
            soundVo.setNickname(byUserId.getNickname());
            soundVo.setId(serviceBySound.getUserId());
            soundVo.setRemainingTimes(userInfo.getRemainingTimes()-1);
            soundVo.setSoundUrl(serviceBySound.getUrl());

            return ResponseEntity.ok(soundVo);
        }else {

            return ResponseEntity.status(500).body("目前还没人传音哦，传个音吧！");

        }

    }
}
